import GameConfig from "GameConfig";
import Player from "Player";
import Wall from "Wall";
import GameTools from "GameTools";

cc.Class({
    extends: cc.Component,

    properties: {
        // 分数展示
        scoreDisplay: cc.Label,
        // 倒计时
        countDown: cc.Prefab,
        // npc
        player: Player,
        // 墙
        leftWall: Wall,
        rightWall: Wall,
        bottomWall: Wall,
        // 固定障碍 - 狼牙棒
        barrierMace: cc.Prefab,
        // 固定障碍 - 钉子
        barrierNail: cc.Prefab,
        // 加分道具 - 勾玉
        bonusMagatama: cc.Prefab,
        // 加分道具 - 葫芦
        bonusCalabash: cc.Prefab,
        // 防护罩
        defense: cc.Prefab,
        // 动态障碍
        dartProps1: cc.Prefab,
        dartProps2: cc.Prefab,
        dartProps3: cc.Prefab,
        // 游戏结束
        gameOverNode: cc.Prefab,
        scoreFxPrefab: cc.Prefab,
        gameOverAudio: {
            type: cc.AudioClip,
            default: null,
        },
        rotationBox: cc.Node,
    },

    onLoad () {
        // 开启碰撞检测
        cc.director.getCollisionManager().enabled = true;
        // 障碍物初始位置设定
        GameConfig.INIT_BARRIER_POSY = GameConfig.WINDOWS_SIZE.height/2 + 200;
        // 游戏开始
        this.gameStart();

        this.defense = cc.instantiate(this.defense);
    },

    gameStart () {
        // 初始化
        this._gameInit();
    },

    _gameInit() {
        // 相关配置初始化
        GameConfig.GAME_READY = false;   // 游戏是否已准备好
        GameConfig.GAME_START = false;   // 游戏是否开始
        GameConfig.GAME_OVER_LAYER_DISPLAY = false;
         // 是否复活后
         if (GameConfig.CHANCE_USED) {
            this.gameContinue();
        } else {
            // 初始化对象池
            this._initPools();
            // 分数归0
            this._resetScore();
            // 初始化ninja
            this.player.init(this, GameConfig.CHOOSEN_ROLE_NAME);
        }
        // 开始倒计时
        this._createCountDown();
    },

    gameContinue() {
        this.player.gameContinue();
    },

    _initPools() {
        // 静态障碍物池
        this.barrierBox = [
            {pref: this.barrierMace, pool: new cc.NodePool('Barrier')},
            {pref: this.barrierNail, pool: new cc.NodePool('Barrier')},
        ];
        // 动态障碍物池
        this.dartBox = [
            {pref: this.dartProps1, pool: new cc.NodePool('DynamicBarrier')},
            {pref: this.dartProps2, pool: new cc.NodePool('DynamicBarrier')},
            {pref: this.dartProps3, pool: new cc.NodePool('DynamicBarrier')},
        ];
        // 保护球池
        this.defenseLevel1Pool = new cc.NodePool('Defense');
        this.defenseLevel2Pool = new cc.NodePool('Defense');
        this.defenseLevel3Pool = new cc.NodePool('Defense');
        // 加分道具池
        this.scorePropsPool = new cc.NodePool('ScoreProps');
        // 加分动画池
        this.scorePool = new cc.NodePool('ScoreFx');
    },

    _resetScore() {
        this.score = 0;
        this.scoreDisplay.string = this.score.toString();
    },

    // 开始倒计时
    _createCountDown() {
        // 倒计时3秒
        var cd = cc.instantiate(this.countDown);
        cd.getComponent("CountDown").init(this.player);
         // 将新增的节点添加到 Canvas 节点下面
        this.node.addChild(cd);
    },

    // 得分
    gainScore(value) {
        value = value ? value : 1;
        this.score += value;
        this.scoreDisplay.string = this.score.toString();
        this._adjustDifficulty();
    },

    // 得分动画
    gainAnim(pos, scoreValue) {
        var newScoreFx = null;
        if (this.scorePool.size() > 0) {
            newScoreFx = this.scorePool.get(this);
        } else {
            newScoreFx = cc.instantiate(this.scoreFxPrefab);
        }
        this.node.addChild(newScoreFx);
        newScoreFx.setPosition(pos);
        newScoreFx.getComponent('ScoreFx').init(this, scoreValue);
    },

    // 根据当前得分调整难度系数
    _adjustDifficulty() {
        var diffLevelScores = GameConfig.DIFFICULTY_LEVEL_SCORE;
        var curScore = this.score;
        var curLevel = GameConfig.LEVEL_OF_DIFFICULTY;
        if (null != diffLevelScores && diffLevelScores.length > 0) {
            for (var i = diffLevelScores.length - 1; i > curLevel - 1; i--) {
                if (curScore >= diffLevelScores[i]) {
                    GameConfig.LEVEL_OF_DIFFICULTY++;
                }
            }
        }
        // 调整移动速度
        var speedLevelScores = GameConfig.SPEED_LEVEL_SCORE;
        if (null != speedLevelScores && speedLevelScores.length > 0) {
            for (var j = speedLevelScores.length - 1; j > 0; j--) {
                if (curScore >= speedLevelScores[j]) {
                    GameConfig.PROPS_PLAYER_MOVE_SPEED = GameConfig.PROPS_PLAYER_MOVE_SPEED_RANGE[j];
                }
            }
        }
    },

    // 生成障碍
    createBarrier() {
        // 概率生成障碍物
        if (this._checkIfCreateBarrier()) {
            if (this._checkIfBarrierStable()) { // 静态障碍物
                this._setupStable();
            } else {
                this._setupDart();
            }
        }
    },
    

    // 是否设置障碍物
    _checkIfCreateBarrier() {
        var rate = (GameConfig.LEVEL_OF_DIFFICULTY - 1) * GameConfig.UNIT_PROBABILITY_OF_BARRIER + GameConfig.INIT_PROBABILITY_OF_BARRIER;
        var rand = Math.round(Math.random()*100);
        return rand <= rate;
    },

    // 是否设置静态障碍物
    _checkIfBarrierStable() {
        return parseInt(Math.random()*3) < 2;
    },

    // 设置静态障碍物
    _setupStable() {
        var newBarrier = GameTools.getInstanceFromBox(this.barrierBox);
        this.rotationBox.addChild(newBarrier);
        var param = GameTools.percent50() ? -1 : 1;  // -1 左 1 右
        var posX = param * (GameConfig.WINDOWS_SIZE.width/2 - newBarrier.width/2 - 67);
        newBarrier.scaleX = param * -1;
        newBarrier.setPosition(posX, GameConfig.INIT_BARRIER_POSY);
        newBarrier.getComponent('Barrier').init(this);
    },

    _instanceBarrier() {
        var random = parent(M)
        var obs = GameTools.percent50() ? this.barrierMace : this.barrierNail;
        return cc.instantiate(obs);
    },

    // 设置动态障碍
    _setupDart() {
        var newDart = GameTools.getInstanceFromBox(this.dartBox);
        this.rotationBox.addChild(newDart);
        var visibleWidth = GameConfig.WINDOWS_SIZE.width - 150;
        var randomX = Math.floor(Math.random()*visibleWidth) - visibleWidth/2;
        newDart.setPosition(randomX, GameConfig.INIT_BARRIER_POSY + GameConfig.BARRIER_UNIT_DISTANCE * 0.8);
        newDart.getComponent('DynamicBarrier').init(this);
    },

    // 设置保护球
    createDefense() {
        if (this.player.status == 0 && this._checkIfCreateDefense()) {
            var lifeCount = this._lifeCount();
            var newDefense = this.defense.getComponent('Defense').createInstance(lifeCount);
            if (newDefense) {
                this.node.addChild(newDefense);
                newDefense.setPosition(cc.v2(0, GameConfig.INIT_BARRIER_POSY - 150));
                newDefense.getComponent('Defense').init(this, GameConfig.INIT_BARRIER_POSY - 150, lifeCount);
            }
        }
    },

    // 随机获取生命数
    _lifeCount() {
        var maxNum = GameConfig.DEFENSE_COUNT_RANGE[1], minNum = GameConfig.DEFENSE_COUNT_RANGE[0];
        return parseInt(Math.random()*(maxNum - minNum + 1) + minNum,10);
    },

    // 设置加分道具
    createScoreProps() {
        if (this._checkIfCreateScoreProps()) {
            var newScoreProps = null;
            if (this.scorePropsPool.size() > 0) {
                newScoreProps = this.scorePropsPool.get(this);
            } else {
                newScoreProps = this._instanceScoreProps();
            }
            this.node.addChild(newScoreProps);
            var visibleWidth = GameConfig.WINDOWS_SIZE.width - 300;
            var randomX = Math.floor(Math.random()*visibleWidth) - visibleWidth/2;
            newScoreProps.setPosition(randomX, GameConfig.INIT_BARRIER_POSY);
            newScoreProps.getComponent('ScoreProps').init(this);
        }
    },

    _instanceScoreProps() {
        var obs = GameTools.percent50() ? this.bonusMagatama : this.bonusCalabash;
        return cc.instantiate(obs);
    },

    // 是否设置保护球
    _checkIfCreateDefense() {
        var rand = Math.round(Math.random()*100);
        return rand <= GameConfig.DEFENSE_RATE;
    },

    // 是否设置加分道具
    _checkIfCreateScoreProps() {
        var rand = Math.round(Math.random()*100);
        return rand <= GameConfig.SCORE_PROPS_RATE;
    },

    // 旋转
    rotateIt() {
        var randomAngle = this._randomRotationAngle();
        this.rotationBox.rotation = randomAngle;
        GameConfig.CURRENT_ROTATION = randomAngle;
    },

    // 随机旋转角度
    _randomRotationAngle() {
        var min = GameConfig.ROTATION_RANGE[0] || -5;
        var max = GameConfig.ROTATION_RANGE[1] || 5;
        return parseInt(Math.random() * (max - min) + min);
    },

    // 游戏结束
    gameOver() {
        GameConfig.GAME_READY = false;
        GameConfig.GAME_START = false;
        // 播放结束音效
        cc.audioEngine.playEffect(this.gameOverAudio, false);
        // 记录结束时忍者位置
        GameConfig.NINJA_POSITION_WHEN_OVER = this.player.node.position;
        // 忍者掉落动画
        this.player.getComponent('Player').fallDown();

        // 清空池
        this._clearPool();
    },

    _clearPool() {
        for (var i = 0, iLen = this.barrierBox.length; i < iLen; i++) {
            this.barrierBox[i].pool.clear();
        }
        for (var j = 0, jLen = this.dartBox.length; j < jLen; j++) {
            this.dartBox[i].pool.clear();
        }
        this.defenseLevel1Pool.clear();
        this.defenseLevel2Pool.clear();
        this.defenseLevel3Pool.clear();
        this.scorePropsPool.clear();
    },

    // 调起结束面板
    overLayer() {
        GameConfig.GAME_OVER_LAYER_DISPLAY = true;
        var gameOverLayer = cc.instantiate(this.gameOverNode);
        gameOverLayer.getComponent("GameOver").init(this);
        this.node.addChild(gameOverLayer);
    },

});
